<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* div{
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
        } */
    </style>
</head>
<body>
    <!-- 输入内容 -->
     <input type="text" placeholder="请输入你的内容" name="" id="">
     <!-- 发送请求 -->
     <button>发送请求</button>
     <button class="btn2">关闭连接</button>
     <!-- 显示结果 -->
     <div></div>

     <script>
         let input = document.querySelector('input');
         let button = document.querySelector('button');
         let btn2 = document.querySelector('.btn2');
         let div = document.querySelector('div')
         //websocket 如何在浏览器使用
         //open 建立连接时触发
         //message 客户端接收服务端数据时触发
         //error 通信发生错误时触发
         //clone连接关闭时触发
         //socket.send()发送连接
         //socket.close()关闭连接
         let socket = new WebSocket('ws://localhost:3000');
         
         socket.addEventListener('open',function(){
            div.innerHTML = '服务连接成功'
         })
         button.addEventListener('click',function(){
             let value = input.value
             console.log('我被点击了')
             socket.send(value)
             input.value = ''
         })

         socket.addEventListener('message',function(e){
            //  let value = input.value
             console.log('我接收到了返回的数据')
             console.log(e)
            //  div.innerHTML = e.data
             let create = document.createElement('div')
             create.innerText = e.data
             div.appendChild(create)
            //  socket.send(value)
         })
         button.addEventListener('click',function(){
             let value = input.value
             console.log('我被点击了')
             socket.send(value)
         })
         btn2.addEventListener('click',function(){
            socket.close()
            //  let value = input.value
             console.log('我关闭了连接')
            //  socket.send(value)
         })
     </script>
</body>
</html>